package com.dd.keel.core.common.ini;

import java.io.File;

import java.util.Iterator;
import java.util.Properties;
import java.util.TreeMap;
import java.util.Enumeration;

/**
 * INI Reader
 * @author Kevin.XU
 *
 */
public class IniReader {
	
	private IniDom iniDom = new IniDom();
	
	public IniReader(File file) throws Exception 
	{
		iniDom.parseFile(file);
	}
	
	public IniReader(String filename) throws Exception 
	{
		iniDom.parseFile(filename);
	}
	
	public IniReader(String filename,Class contextClass) throws Exception 
	{
		iniDom.parseFile(filename,contextClass);
	}
	
	public IniReader(File file,boolean useSplash) throws Exception 
	{
		iniDom.setUseSplash(useSplash);
		iniDom.parseFile(file);
	}
	
	public IniReader(String filename,boolean useSplash) throws Exception 
	{
		iniDom.setUseSplash(useSplash);
		iniDom.parseFile(filename);
	}
	
	public IniReader(String filename,boolean useSplash,Class contextClass) throws Exception 
	{
		iniDom.setUseSplash(useSplash);
		iniDom.parseFile(filename,contextClass);
	}
	
	public String getValue(String section, String name) {
		return iniDom.getValue(section, name);
	}
	
	public Properties getSectionProps(String section) 
	{
		TreeMap<String,String> treeProps = iniDom.getSection(section);
		if(treeProps==null) return new Properties();
		Properties props = new Properties();
		Iterator<String> keyIter = treeProps.keySet().iterator();
		while(keyIter.hasNext())
		{
			String key =  keyIter.next();
			String value = treeProps.get(key);
			if(key!=null) key = key.trim();
			if(value!=null) value = value.trim();
			if(key!=null && !key.equals("") && value!=null ) // && !value.equals(""))
			{
				props.put(key, value);
			}
		}
		return props;
	}
	
	public void getSectionProps(String section,Properties props) 
	{
		TreeMap<String,String> treeProps = iniDom.getSection(section);
		if(treeProps==null) return;
		Iterator<String> keyIter = treeProps.keySet().iterator();
		while(keyIter.hasNext())
		{
			String key =  keyIter.next();
			String value = treeProps.get(key);
			if(key!=null) key = key.trim();
			if(value!=null) value = value.trim();
			if(key!=null && !key.equals("") && value!=null ) // && !value.equals(""))
			{
				props.put(key, value);
			}
		}
	}
	
	public Properties getSectionProps(String section,String keyPrefix) 
	{
		Properties props = getSectionProps(section);
		if(props!=null && !props.isEmpty())
		{
			Properties result = new Properties();
			Enumeration keyIter = props.keys();
			while(keyIter.hasMoreElements())
			{
				String key = (String)keyIter.nextElement();
				String value = props.getProperty(key);
				if(key.startsWith(keyPrefix))
				{
					result.put(key, value);
				}
			}
			return result;
		}
		return new Properties();
	}
	
	/**
	 * all section names
	 * @return
	 */
	public Iterator<String> getAllSectionNames() {
		return iniDom.allSectionNames();
	}
}
